using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Domain.DTOs;
using CPlatePrintSys.Application.Services;
using Prism.Commands;
using Prism.Mvvm;
using System.Windows.Forms;
using CPlatePrintSys.Infrastructure.Repositories;

namespace CPlatePrintSys.Win.ViewModels
{
    public class InterfaceConfigTabbedViewModel : BindableBase
    {
        private readonly IGlobalConfigService _configService;
        private readonly KmacsService _kmacsService;
        private readonly AmService _amService;
        private readonly CadWinService _cadWinService;
        private readonly DataSyncService _dataSyncService;

        #region 标签页管理
        private int _selectedTabIndex = 2; // 默认选择Aveva Marine
        public int SelectedTabIndex
        {
            get => _selectedTabIndex;
            set 
            {
                if (SetProperty(ref _selectedTabIndex, value))
                {
                    UpdateTabVisibility();
                }
            }
        }

        private string _selectedTabName = "Aveva Marine";
        public string SelectedTabName
        {
            get => _selectedTabName;
            set => SetProperty(ref _selectedTabName, value);
        }

        private bool _isKmacsTabVisible = false;
        public bool IsKmacsTabVisible
        {
            get => _isKmacsTabVisible;
            set => SetProperty(ref _isKmacsTabVisible, value);
        }

        private bool _isCadWinTabVisible = false;
        public bool IsCadWinTabVisible
        {
            get => _isCadWinTabVisible;
            set => SetProperty(ref _isCadWinTabVisible, value);
        }

        private bool _isAvevaMarineTabVisible = true;
        public bool IsAvevaMarineTabVisible
        {
            get => _isAvevaMarineTabVisible;
            set => SetProperty(ref _isAvevaMarineTabVisible, value);
        }
        #endregion

        #region K-Macs 配置
        private string _kmacsHttpMethod = "GET";
        public string KmacsHttpMethod
        {
            get => _kmacsHttpMethod;
            set => SetProperty(ref _kmacsHttpMethod, value);
        }

        private string _kmacsApiUrl = "http://192.168.1.0/biz/getInfo";
        public string KmacsApiUrl
        {
            get => _kmacsApiUrl;
            set => SetProperty(ref _kmacsApiUrl, value);
        }

        private ObservableCollection<KmacsDataItem> _kmacsDataItems = new ObservableCollection<KmacsDataItem>();
        public ObservableCollection<KmacsDataItem> KmacsDataItems
        {
            get => _kmacsDataItems;
            set => SetProperty(ref _kmacsDataItems, value);
        }
        #endregion

        #region CADWin 配置
        private string _cadWinSharePath = @"\\192.168.2.3\CADWin\";
        public string CadWinSharePath
        {
            get => _cadWinSharePath;
            set => SetProperty(ref _cadWinSharePath, value);
        }

        private ObservableCollection<CadWinDataItem> _cadWinDataItems = new ObservableCollection<CadWinDataItem>();
        public ObservableCollection<CadWinDataItem> CadWinDataItems
        {
            get => _cadWinDataItems;
            set => SetProperty(ref _cadWinDataItems, value);
        }
        #endregion

        #region Aveva Marine 配置
        private string _avevaMarineDatabaseUrl = "MySql://192.168.2.3:6603/AM_Data";
        public string AvevaMarineDatabaseUrl
        {
            get => _avevaMarineDatabaseUrl;
            set => SetProperty(ref _avevaMarineDatabaseUrl, value);
        }

        private ObservableCollection<AvevaMarineDataItem> _avevaMarineDataItems = new ObservableCollection<AvevaMarineDataItem>();
        public ObservableCollection<AvevaMarineDataItem> AvevaMarineDataItems
        {
            get => _avevaMarineDataItems;
            set => SetProperty(ref _avevaMarineDataItems, value);
        }
        #endregion

        #region 状态消息
        private string _statusMessage;
        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }
        #endregion

        #region 数据加载状态跟踪
        private bool _isKmacsDataLoaded = false;
        public bool IsKmacsDataLoaded
        {
            get => _isKmacsDataLoaded;
            set => SetProperty(ref _isKmacsDataLoaded, value);
        }

        private bool _isCadWinDataLoaded = false;
        public bool IsCadWinDataLoaded
        {
            get => _isCadWinDataLoaded;
            set => SetProperty(ref _isCadWinDataLoaded, value);
        }

        private bool _isAvevaMarineDataLoaded = false;
        public bool IsAvevaMarineDataLoaded
        {
            get => _isAvevaMarineDataLoaded;
            set => SetProperty(ref _isAvevaMarineDataLoaded, value);
        }
        #endregion

        #region 命令
        public ICommand TestConnectionCommand { get; }
        public ICommand RefreshDataCommand { get; }
        public ICommand RefreshKmacsDataCommand { get; }
        public ICommand RefreshCadWinDataCommand { get; }
        public ICommand RefreshAmDataCommand { get; }
        public ICommand SelectCadWinDirectoryCommand { get; }
        public ICommand SaveConfigCommand { get; }
        public ICommand SwitchTabCommand { get; }
        #endregion

        public InterfaceConfigTabbedViewModel(IGlobalConfigService configService, IPlateAnnotationInfoRepository plateAnnotationRepository, ShipInfoService shipInfoService)
        {
            _configService = configService;
            _kmacsService = new KmacsService();
            _amService = new AmService();
            _cadWinService = new CadWinService();
            _dataSyncService = new DataSyncService(plateAnnotationRepository, _kmacsService, _amService, _cadWinService, shipInfoService);

            TestConnectionCommand = new DelegateCommand(TestConnection);
            RefreshDataCommand = new DelegateCommand(async () => await RefreshDataAsync());
            RefreshKmacsDataCommand = new DelegateCommand(async () => await RefreshKmacsDataAsync());
            RefreshCadWinDataCommand = new DelegateCommand(async () => await RefreshCadWinDataAsync());
            RefreshAmDataCommand = new DelegateCommand(async () => await RefreshAmDataAsync());
            SelectCadWinDirectoryCommand = new DelegateCommand(SelectCadWinDirectory);
            SaveConfigCommand = new DelegateCommand(async () => await SaveConfig());
            SwitchTabCommand = new DelegateCommand<string>(SwitchTab);

            LoadConfig();
            // 移除自动加载数据，改为按需加载
        }

        private async void LoadConfig()
        {
            try
            {
                var config = await _configService.GetInterfaceConfigAsync();
                if (config != null)
                {
                    KmacsHttpMethod = config.KmacsHttpMethod ?? "GET";
                    KmacsApiUrl = config.KmacsApiUrl ?? "http://192.168.1.0/biz/getInfo";
                    CadWinSharePath = config.CadWinSharePath ?? @"\\192.168.2.3\CADWin\";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载配置失败: {ex.Message}";
            }
        }

        private async Task SaveConfig()
        {
            try
            {
                StatusMessage = "正在保存配置...";
                
                var config = new InterfaceConfig
                {
                    KmacsHttpMethod = KmacsHttpMethod,
                    KmacsApiUrl = KmacsApiUrl,
                    CadWinSharePath = CadWinSharePath,
                    TimeoutSeconds = 30,
                    EnableCache = true,
                    CacheExpirationMinutes = 10
                };

                await _configService.UpdateInterfaceConfigAsync(config, "System");
                StatusMessage = "配置保存成功";
                
                await Task.Delay(1500);
                StatusMessage = "";
            }
            catch (Exception ex)
            {
                StatusMessage = $"保存失败: {ex.Message}";
            }
        }

        private void TestConnection()
        {
            try
            {
                StatusMessage = "正在测试连接...";
                
                // 模拟测试连接
                Task.Delay(1000).ContinueWith(_ =>
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        StatusMessage = "连接测试成功";
                        Task.Delay(1500).ContinueWith(__ =>
                        {
                            App.Current.Dispatcher.Invoke(() => StatusMessage = "");
                        });
                    });
                });
            }
            catch (Exception ex)
            {
                StatusMessage = $"连接测试失败: {ex.Message}";
            }
        }

        private async Task RefreshDataAsync()
        {
            try
            {
                StatusMessage = "正在刷新数据并同步到数据库...";
                
                // 只同步当前可见标签页的数据
                if (IsKmacsTabVisible)
                {
                    await RefreshKmacsDataAsync();
                }
                else if (IsCadWinTabVisible)
                {
                    await RefreshCadWinDataAsync();
                }
                else if (IsAvevaMarineTabVisible)
                {
                    await RefreshAmDataAsync();
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"数据刷新失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 分步骤刷新数据并同步到数据库
        /// </summary>
        private async Task<DataSyncResult> RefreshDataStepByStepAsync()
        {
            var result = new DataSyncResult();
            
            try
            {
                // 步骤1：先同步Kmacs数据（基础数据）
                StatusMessage = "正在同步Kmacs数据...";
                result.KmacsSyncResult = await _dataSyncService.SyncKmacsDataOnlyAsync();
                
                // 步骤2：同步CadWin数据（基于已入库的Kmacs数据进行关联补充）
                StatusMessage = "正在同步CadWin数据...";
                result.CadWinSyncResult = await _dataSyncService.SyncCadWinDataOnlyAsync();
                
                // 步骤3：同步AM数据（基于已入库的Kmacs数据进行关联补充）
                StatusMessage = "正在同步AM数据...";
                result.AmSyncResult = await _dataSyncService.SyncAmDataOnlyAsync();
                
                result.IsSuccess = result.KmacsSyncResult.IsSuccess && 
                                 result.CadWinSyncResult.IsSuccess && 
                                 result.AmSyncResult.IsSuccess;
                
                if (result.IsSuccess)
                {
                    result.Message = $"同步完成 - Kmacs:{result.KmacsSyncResult.AddedRecords + result.KmacsSyncResult.UpdatedRecords}条, " +
                                   $"CadWin:{result.CadWinSyncResult.AddedRecords + result.CadWinSyncResult.UpdatedRecords}条, " +
                                   $"AM:{result.AmSyncResult.AddedRecords + result.AmSyncResult.UpdatedRecords}条";
                }
                else
                {
                    result.Message = "部分数据同步失败";
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = $"分步骤同步失败: {ex.Message}";
                result.Exception = ex;
            }
            
            return result;
        }

        /// <summary>
        /// 刷新Kmacs数据并同步到数据库
        /// </summary>
        private async Task RefreshKmacsDataAsync()
        {
            try
            {
                StatusMessage = "正在刷新Kmacs数据...";
                
                // 1. 先加载Kmacs数据到UI显示
                await LoadKmacsDataAsync();
                
                // 2. 同步Kmacs数据到数据库
                var syncResult = await _dataSyncService.SyncKmacsDataOnlyAsync();
                
                if (syncResult.IsSuccess)
                {
                    StatusMessage = $"Kmacs数据刷新成功 - {syncResult.Message}";
                }
                else
                {
                    StatusMessage = $"Kmacs数据同步失败: {syncResult.Message}";
                }
                
                await Task.Delay(1500);
                StatusMessage = "";
            }
            catch (Exception ex)
            {
                StatusMessage = $"Kmacs数据刷新失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 刷新CadWin数据并同步到数据库
        /// </summary>
        private async Task RefreshCadWinDataAsync()
        {
            try
            {
                StatusMessage = "正在刷新CadWin数据...";
                
                // 1. 先加载CadWin数据到UI显示
                await LoadCadWinDataAsync();
                
                // 2. 同步CadWin数据到数据库（基于已入库的Kmacs数据进行关联补充）
                var syncResult = await _dataSyncService.SyncCadWinDataOnlyAsync();
                
                if (syncResult.IsSuccess)
                {
                    StatusMessage = $"CadWin数据刷新成功 - {syncResult.Message}";
                }
                else
                {
                    StatusMessage = $"CadWin数据同步失败: {syncResult.Message}";
                }
                
                await Task.Delay(1500);
                StatusMessage = "";
            }
            catch (Exception ex)
            {
                StatusMessage = $"CadWin数据刷新失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 刷新AM数据并同步到数据库
        /// </summary>
        private async Task RefreshAmDataAsync()
        {
            try
            {
                StatusMessage = "正在刷新AM数据...";
                
                // 1. 先加载AM数据到UI显示
                await LoadAvevaMarineDataAsync();
                
                // 2. 同步AM数据到数据库（基于已入库的Kmacs数据进行关联补充）
                var syncResult = await _dataSyncService.SyncAmDataOnlyAsync();
                
                if (syncResult.IsSuccess)
                {
                    StatusMessage = $"AM数据刷新成功 - {syncResult.Message}";
                }
                else
                {
                    StatusMessage = $"AM数据同步失败: {syncResult.Message}";
                }
                
                await Task.Delay(1500);
                StatusMessage = "";
            }
            catch (Exception ex)
            {
                StatusMessage = $"AM数据刷新失败: {ex.Message}";
            }
        }

        private void SelectCadWinDirectory()
        {
            try
            {
                var dialog = new FolderBrowserDialog
                {
                    Description = "选择CADWin共享目录",
                    ShowNewFolderButton = false
                };

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    CadWinSharePath = dialog.SelectedPath + "\\";
                    StatusMessage = "目录选择成功";
                    
                    Task.Delay(1500).ContinueWith(_ =>
                    {
                        App.Current.Dispatcher.Invoke(() => StatusMessage = "");
                    });
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"选择目录失败: {ex.Message}";
            }
        }

        private void SwitchTab(string tabIndex)
        {
            if (int.TryParse(tabIndex, out int index))
            {
                SelectedTabIndex = index;
                switch (index)
                {
                    case 0:
                        SelectedTabName = "K-Macs";
                        break;
                    case 1:
                        SelectedTabName = "CADWin";
                        break;
                    case 2:
                        SelectedTabName = "Aveva Marine";
                        break;
                }
            }
        }

        private void UpdateTabVisibility()
        {
            IsKmacsTabVisible = SelectedTabIndex == 0;
            IsCadWinTabVisible = SelectedTabIndex == 1;
            IsAvevaMarineTabVisible = SelectedTabIndex == 2;
        }

        private async Task LoadRealData()
        {
            try
            {
                // 加载K-Macs真实数据
                await LoadKmacsDataAsync();
                
                // 加载CADWin真实数据
                await LoadCadWinDataAsync();
                
                // 加载Aveva Marine真实数据
                await LoadAvevaMarineDataAsync();
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载数据失败: {ex.Message}";
            }
        }

        private async Task LoadKmacsDataAsync()
        {
            try
            {
                var kmacsData = await _kmacsService.GetProcessInfosAsync();
                KmacsDataItems.Clear();
                
                foreach (var item in kmacsData)
                {
                    KmacsDataItems.Add(new KmacsDataItem
                    {
                        StreamShipNo = item.StreamShipNo,
                        LotNo = item.LotNo,
                        SheetConsistentNo = item.SheetConsistentNo,
                        CNO = item.CNO,
                        Sequence = item.Sequence,
                        SheetSpecCls = item.SheetSpecCls,
                        SheetSpecThickness = item.SheetSpecThickness,
                        SheetSpecWidth = item.SheetSpecWidth,
                        SheetSpecLength = item.SheetSpecLength,
                        PlanUsedDate = item.PlanUsedDate?.ToString("yyyy-MM-dd") ?? ""
                    });
                }
                
                IsKmacsDataLoaded = true;
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载K-Macs数据失败: {ex.Message}";
            }
        }

        private async Task LoadCadWinDataAsync()
        {
            try
            {
                var cadWinData = await _cadWinService.GetDrawingInfosAsync();
                CadWinDataItems.Clear();
                
                foreach (var item in cadWinData)
                {
                    CadWinDataItems.Add(new CadWinDataItem
                    {
                        ShipNo = item.ShipNo,
                        LotNo = item.LotNo,
                        Sequence = item.Sequence,
                        PlateNo = item.PlateNo,
                        CNO = item.CNO,
                        DesignSpecCls = item.DesignSpecCls,
                        DesignSpecThickness = item.DesignSpecThickness,
                        DesignSpecLength = item.DesignSpecLength,
                        DesignSpecWidth = item.DesignSpecWidth,
                        DxfPath = item.DxfPath
                    });
                }
                
                IsCadWinDataLoaded = true;
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载CADWin数据失败: {ex.Message}";
            }
        }

        private async Task LoadAvevaMarineDataAsync()
        {
            try
            {
                var amData = await _amService.GetDrawingInfosAsync();
                AvevaMarineDataItems.Clear();
                
                foreach (var item in amData)
                {
                    AvevaMarineDataItems.Add(new AvevaMarineDataItem
                    {
                        ShipNo = item.ShipNo,
                        LotNo = item.LotNo,
                        Sequence = item.Sequence,
                        PlateNo = item.PlateNo,
                        CNO = item.CNO,
                        DesignSpecCls = item.DesignSpecCls,
                        DesignSpecThickness = item.DesignSpecThickness,
                        DesignSpecLength = item.DesignSpecLength,
                        DesignSpecWidth = item.DesignSpecWidth,
                        N = item.NFlag,
                        M = item.MFlag,
                        SdbPath = item.SdbPath
                    });
                }
                
                IsAvevaMarineDataLoaded = true;
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载Aveva Marine数据失败: {ex.Message}";
            }
        }
    }

    #region 数据模型
    public class KmacsDataItem : BindableBase
    {
        public string StreamShipNo { get; set; }
        public string LotNo { get; set; }

        public string Sequence { get; set; }
        public string SheetConsistentNo { get; set; }
        public string CNO { get; set; }
        public string SheetSpecCls { get; set; }
        public double SheetSpecThickness { get; set; }
        public double SheetSpecWidth { get; set; }
        public double SheetSpecLength { get; set; }
        public string PlanUsedDate { get; set; }
    }

    public class CadWinDataItem : BindableBase
    {
        public string ShipNo { get; set; }
        public string LotNo { get; set; }
        public string Sequence { get; set; }
        public string CNO { get; set; }
        public string PlateNo { get; set; }
        public string DesignSpecCls { get; set; }
        public double DesignSpecThickness { get; set; }
        public double DesignSpecLength { get; set; }
        public double DesignSpecWidth { get; set; }
        public string DxfPath { get; set; }
    }

    public class AvevaMarineDataItem : BindableBase
    {
        public string ShipNo { get; set; }
        public string LotNo { get; set; }
        public string Sequence { get; set; }
        public string CNO { get; set; }
        public string PlateNo { get; set; }
        public string DesignSpecCls { get; set; }
        public double DesignSpecThickness { get; set; }
        public double DesignSpecLength { get; set; }
        public double DesignSpecWidth { get; set; }
        public int N { get; set; }
        public int M { get; set; }
        public string SdbPath { get; set; }
    }
    #endregion
}
